//
//  DNCryingDao.m
//  DanoneEA
//
//  Created by 3ti_Jery on 16/10/19.
//  Copyright © 2016年 翔傲科技. All rights reserved.
//

#import "DNCryingDao.h"
#import "DNUserManager.h"

@implementation DNCryingDao

+ (NSString *) getCreateSQL
{
    return [NSString
            stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (%@ text primary key,%@ text,%@ text,%@ integer,%@ text,%@ text,%@ text,%@ text,%@ text,%@ text,%@ text,%@ integer,%@ text,%@ text,%@ text);",
            Crying_TABLE,
            DairyBase_AppId,
            DairyBase_ServerId,
            DairyBase_InfantId,
            DairyBase_Status,
            DairyBase_ModifyReason,
            DairyBase_DeleteReason,
            DairyBase_CreateTime,
            DairyBase_ModifyTime,
            DairyBase_DeleteTime,
            DairyBase_Ddat,
            Crying_CryType,
            Crying_TimeOfDay,
            Crying_CryInyn,
            Crying_CrySttime,
            Crying_CryEntime
            ];
    
}

+ (NSString *) getInsertSQL
{
    return [NSString stringWithFormat:@"REPLACE INTO %@(%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);",
            Crying_TABLE,
            DairyBase_AppId,
            DairyBase_ServerId,
            DairyBase_InfantId,
            DairyBase_Status,
            DairyBase_ModifyReason,
            DairyBase_DeleteReason,
            DairyBase_CreateTime,
            DairyBase_ModifyTime,
            DairyBase_DeleteTime,
            DairyBase_Ddat,
            Crying_CryType,
            Crying_TimeOfDay,
            Crying_CryInyn,
            Crying_CrySttime,
            Crying_CryEntime
            ];
    
}

#pragma mark - add

- (BOOL)saveCryingModel:(DNCryingModel *) object
{
    DNDataBase *dataBase = [DNDataBase shareInstance];
    __block BOOL ret = NO;
    
    [dataBase.dbQueue inDatabase:^(FMDatabase *db) {
        if(![db open])
        {
            db = nil;
            return;
        }else{
            [db setKey:DB_SECRETKEY];
            
            ret = [db executeUpdate:[DNCryingDao getInsertSQL],
                   object.appId,
                   object.serverId,
                   object.infantId,
                   object.status,
                   object.modifyReason,
                   object.deleteReason,
                   object.createTime,
                   object.modifyTime,
                   object.deleteTime,
                   object.ddat,
                   object.cryType,
                   object.timeOfDay,
                   object.cryInyn,
                   object.crySttime,
                   object.cryEntime
                   ];
            
            if (!ret) {
                ret = NO;
                [db rollback];;
                DDLogError(@"Update error AppId:%@",
                           object.appId);
                [db close];
                return;
            }
        }
        [db close];
    }];
    
    return ret;
}

- (BOOL) saveCryingModelWithArray:(NSArray *)objectList{
    
    __block BOOL ret = YES;
    DNDataBase *dataBase = [DNDataBase shareInstance];
    // 如果要支持事务
    [dataBase.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        [db setKey:DB_SECRETKEY];
        
        for (DNCryingModel *object in objectList) {
            
            ret =[db executeUpdate:[DNCryingDao getInsertSQL],
                  object.appId,
                  object.serverId,
                  object.infantId,
                  object.status,
                  object.modifyReason,
                  object.deleteReason,
                  object.createTime,
                  object.modifyTime,
                  object.deleteTime,
                  object.ddat,
                  object.cryType,
                  object.timeOfDay,
                  object.cryInyn,
                  object.crySttime,
                  object.cryEntime
                  ];
            
            if (!ret) {
                ret = NO;
                *rollback = YES;
                DDLogError(@"Update error AppId:%@",
                           object.appId);
                return;
            }
        }
    }];
    
    return ret;
    
    
    /*
     FMDatabase *database = [AppDelegate getDatabase];
     BOOL ret = NO;
     if(![database open])
     {
     database = nil;
     return ret;
     }
     else
     [database setKey:DB_SECRETKEY];
     
     if(objectList != nil){
     [database beginTransaction];
     for(DNCryingModel *object in objectList){
     ret =[database executeUpdate:[DNCryingDao getInsertSQL],
     object.appId,
     object.serverId,
     object.infantId,
     object.status,
     object.modifyReason,
     object.deleteReason,
     object.createTime,
     object.modifyTime,
     object.deleteTime,
     object.ddat,
     object.cryType,
     object.timeOfDay,
     object.cryInyn,
     object.crySttime,
     object.cryEntime
     ];
     if(!ret){
     [database rollback];
     DDLogError(@"Update error AppId:%@",
     object.appId);
     [database close];
     return ret;
     }
     }
     [database commit];
     }
     [database close];
     return ret;
     */
}

#pragma mark - delete

- (BOOL)deleteCryingModelByAppId:(NSString *)appId
{
    
    DNDataBase *dnDB = [DNDataBase shareInstance];
    __block BOOL ret = NO;
    [dnDB.dbQueue inDatabase:^(FMDatabase *db) {
        
        if(![db open])
        {
            db = nil;
            return;
        }
        else
            [db setKey:DB_SECRETKEY];
        
        NSString * deleteSQL = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = %@;",Crying_TABLE,DairyBase_AppId,appId];
        ret = [db executeUpdate:deleteSQL];
        [db close];
        
    }];
    return ret;
    
}

#pragma mark - update

- (BOOL)updateCryingModel:(DNCryingModel *)object
{
    
    DNDataBase *dnDB = [DNDataBase shareInstance];
    __block BOOL ret = NO;
    
    [dnDB.dbQueue inDatabase:^(FMDatabase *db) {
        if(![db open])
        {
            db = nil;
            return;
        }
        else
            [db setKey:DB_SECRETKEY];
        
        NSString * updateString = [NSString stringWithFormat:@"UPDATE %@ SET %@ = '%@' ,%@ = '%@',%@ = %@,%@ = '%@',%@ = '%@',%@ = '%@',%@ = '%@',%@ = '%@',%@ = '%@',%@ = %@,%@ = '%@',%@ = '%@',%@ = '%@',%@ = '%@' WHERE %@ = '%@'",
                                   Crying_TABLE,
                                   DairyBase_ServerId,object.serverId,
                                   DairyBase_InfantId,object.infantId,
                                   DairyBase_Status,object.status,
                                   DairyBase_ModifyReason,object.modifyReason,
                                   DairyBase_DeleteReason,object.deleteReason,
                                   DairyBase_CreateTime,object.createTime,
                                   DairyBase_ModifyTime,object.modifyTime,
                                   DairyBase_DeleteTime,object.deleteTime,
                                   DairyBase_Ddat,object.ddat,
                                   Crying_CryType,object.cryType,
                                   Crying_TimeOfDay,object.timeOfDay,
                                   Crying_CryInyn,object.cryInyn,
                                   Crying_CrySttime,object.crySttime,
                                   Crying_CryEntime,object.cryEntime,
                                   DairyBase_AppId,object.appId
                                   ];
        ret = [db executeUpdate:updateString];
        [db close];
    }];
    return ret;
    
}

- (BOOL)updateCryingModelByAppId:(NSString *)appId
{
    DNDataBase *dnDB = [DNDataBase shareInstance];
    __block BOOL ret = NO;
    
    [dnDB.dbQueue inDatabase:^(FMDatabase *db) {
        if(![db open])
        {
            db = nil;
            return;
        }
        else
            [db setKey:DB_SECRETKEY];
        
        DNCryingModel *object = [self getObjectModelByAppId:appId];
        NSString * updateString = [NSString stringWithFormat:@"UPDATE %@ SET %@ = '%@' WHERE %@ = '%@'",
                                   Crying_TABLE,
                                   DairyBase_Status,object.status,
                                   DairyBase_AppId,object.appId
                                   
                                   ];
        ret = [db executeUpdate:updateString];
        [db close];
    }];
    return ret;
    
    /*
     FMDatabase *database = [AppDelegate getDatabase];
     BOOL ret = NO;
     if(![database open])
     {
     database = nil;
     return ret;
     }
     else
     [database setKey:DB_SECRETKEY];
     
     DNCryingModel *object = [self getObjectModelByAppId:appId];
     
     NSString * updateString = [NSString stringWithFormat:@"UPDATE %@ SET %@ = '%@' WHERE %@ = '%@'",
     Crying_TABLE,
     DairyBase_Status,object.status,
     DairyBase_AppId,object.appId
     
     ];
     [database executeUpdate:updateString];
     [database close];
     
     return ret;
     */
}

#pragma mark - query

-(DNCryingModel *) queryCryingModelWithCrySttime:(NSString *)crySttime andcryEndtime:(NSString *)cryEndtime
{
    
    DNDataBase *dnDB = [DNDataBase shareInstance];
    __block DNCryingModel *object = nil;
    
    [dnDB.dbQueue inDatabase:^(FMDatabase *db) {
        
        if(![db open])
        {
            db = nil;
            return;
        }
        else
            [db setKey:DB_SECRETKEY];
        
        // Senela Add:2016-11-2; @"SELECT * FROM %@ WHERE ('%@' < %@ AND '%@' > %@);"
        NSString * querySQL = [ NSString stringWithFormat:@"SELECT * FROM %@ WHERE not (('%@' >= %@) or ('%@' <= %@));",Crying_TABLE,crySttime,Crying_CryEntime,cryEndtime,Crying_CrySttime];
        
        //        NSString * querySQL = [ NSString stringWithFormat:@"SELECT * FROM %@ WHERE ('%@' < %@ AND '%@' > %@);",Crying_TABLE,crySttime,Crying_CryEntime,cryEndtime,Crying_CrySttime];
        
        FMResultSet *rs = [db executeQuery:querySQL];
        while ([rs next]) {
            object = [[DNCryingModel alloc] init];
            [object setAppId:[rs stringForColumn:DairyBase_AppId]];
            [object setServerId:[rs stringForColumn:DairyBase_ServerId]];
            [object setInfantId:[rs stringForColumn:DairyBase_InfantId]];
            [object setStatus:[NSNumber numberWithInt:[[rs stringForColumn:DairyBase_Status] intValue]]];
            [object setModifyTime:[rs stringForColumn:DairyBase_ModifyReason]];
            [object setDeleteReason:[rs stringForColumn:DairyBase_DeleteReason]];
            [object setCreateTime:[rs stringForColumn:DairyBase_CreateTime]];
            [object setModifyTime:[rs stringForColumn:DairyBase_ModifyTime]];
            [object setDeleteTime:[rs stringForColumn:DairyBase_DeleteTime]];
            [object setDdat:[rs stringForColumn:DairyBase_Ddat]];
            [object setCryType:[NSNumber numberWithInt:[[rs stringForColumn:Crying_CryType] intValue]]];
            [object setTimeOfDay:[rs stringForColumn:Crying_TimeOfDay]];
            [object setCrySttime:[rs stringForColumn:Crying_CrySttime]];
            [object setCryEntime:[rs stringForColumn:Crying_CryEntime]];
        }
        [db close];
    }];
    
    return object;
    
}

-(DNCryingModel *) queryCryingModelWithCrySttime:(NSString *)crySttime
{
    
    DNDataBase *dnDB = [DNDataBase shareInstance];
    __block DNCryingModel *object = nil;
    
    [dnDB.dbQueue inDatabase:^(FMDatabase *db) {
        
        if(![db open])
        {
            db = nil;
            return;
        }
        else
            [db setKey:DB_SECRETKEY];
        
        NSString * querySQL = [ NSString stringWithFormat:@"SELECT * FROM %@ WHERE ('%@' < cryEntime AND '%@' > cryEntime);",Crying_TABLE,crySttime,crySttime];
        
        FMResultSet *rs = [db executeQuery:querySQL];
        while ([rs next]) {
            
            [object setAppId:[rs stringForColumn:DairyBase_AppId]];
            [object setServerId:[rs stringForColumn:DairyBase_ServerId]];
            [object setInfantId:[rs stringForColumn:DairyBase_InfantId]];
            [object setStatus:[NSNumber numberWithInt:[[rs stringForColumn:DairyBase_Status] intValue]]];
            [object setModifyTime:[rs stringForColumn:DairyBase_ModifyReason]];
            [object setDeleteReason:[rs stringForColumn:DairyBase_DeleteReason]];
            [object setCreateTime:[rs stringForColumn:DairyBase_CreateTime]];
            [object setModifyTime:[rs stringForColumn:DairyBase_ModifyTime]];
            [object setDeleteTime:[rs stringForColumn:DairyBase_DeleteTime]];
            [object setDdat:[rs stringForColumn:DairyBase_Ddat]];
            [object setCryType:[NSNumber numberWithInt:[[rs stringForColumn:Crying_CryType] intValue]]];
            [object setTimeOfDay:[rs stringForColumn:Crying_TimeOfDay]];
            [object setCrySttime:[rs stringForColumn:Crying_CrySttime]];
            [object setCryEntime:[rs stringForColumn:Crying_CryEntime]];
        }
        [db close];
    }];
    
    return object;
    
}

- (BOOL)iSOverlapInDBCurrentCryingModel:(DNCryingModel *)object
{
    DNCryingModel * existedObject = [self queryCryingModelWithCrySttime:object.crySttime andcryEndtime:object.cryEntime];
    if(existedObject){
        return YES;
    }else {
        return NO;
    }
}

- (DNCryingModel *)getObjectModelByAppId:(NSString *)appId{
    
    DNDataBase *dnDB = [DNDataBase shareInstance];
    __block DNCryingModel *object = nil;
    
    [dnDB.dbQueue inDatabase:^(FMDatabase *db) {
        
        if(![db open])
        {
            db = nil;
            return;
        }
        else
            [db setKey:DB_SECRETKEY];
        
        FMResultSet *rs = [db executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ where %@ = %@",Crying_TABLE,DairyBase_AppId,appId]];
        
        while ([rs next]) {
            object = [[DNCryingModel alloc] init];
            [object setAppId:[rs stringForColumn:DairyBase_AppId]];
            [object setServerId:[rs stringForColumn:DairyBase_ServerId]];
            [object setInfantId:[rs stringForColumn:DairyBase_InfantId]];
            [object setStatus:[NSNumber numberWithInt:[[rs stringForColumn:DairyBase_Status] intValue]]];
            [object setModifyTime:[rs stringForColumn:DairyBase_ModifyReason]];
            [object setDeleteReason:[rs stringForColumn:DairyBase_DeleteReason]];
            [object setCreateTime:[rs stringForColumn:DairyBase_CreateTime]];
            [object setModifyTime:[rs stringForColumn:DairyBase_ModifyTime]];
            [object setDeleteTime:[rs stringForColumn:DairyBase_DeleteTime]];
            [object setDdat:[rs stringForColumn:DairyBase_Ddat]];
            [object setCryType:[NSNumber numberWithInt:[[rs stringForColumn:Crying_CryType] intValue]]];
            [object setTimeOfDay:[rs stringForColumn:Crying_TimeOfDay]];
            [object setCrySttime:[rs stringForColumn:Crying_CrySttime]];
            [object setCryEntime:[rs stringForColumn:Crying_CryEntime]];
        }
        [db close];
    }];
    
    return object;
}


- (NSMutableArray *)getAllObjectModelNotSynchronized
{
    DNDataBase *dnDB = [DNDataBase shareInstance];
    NSMutableArray *items = [[NSMutableArray alloc] init];
    [dnDB.dbQueue inDatabase:^(FMDatabase *db) {
        
        if(![db open])
        {
            db = nil;
            return;
        }
        else
            [db setKey:DB_SECRETKEY];
        
        NSString *synchronousDays = [[DNUserManager sharedInstance] getValueFromDefaultWithKey:UserDefaultKey_SynchronousDays];
        
        NSString * queryString =  [self getQueryAllModelSqlWithTableName:Crying_TABLE andBeforeDays:synchronousDays.intValue];
        FMResultSet *rs = [db executeQuery:queryString];
        while ([rs next]) {
            DNCryingModel *object = [[DNCryingModel alloc] init];
            
            [object setAppId:[rs stringForColumn:DairyBase_AppId]];
            [object setServerId:[rs stringForColumn:DairyBase_ServerId]];
            [object setInfantId:[rs stringForColumn:DairyBase_InfantId]];
            [object setStatus:[NSNumber numberWithInt:[[rs stringForColumn:DairyBase_Status] intValue]]];
            [object setModifyTime:[rs stringForColumn:DairyBase_ModifyReason]];
            [object setDeleteReason:[rs stringForColumn:DairyBase_DeleteReason]];
            [object setCreateTime:[rs stringForColumn:DairyBase_CreateTime]];
            [object setModifyTime:[rs stringForColumn:DairyBase_ModifyTime]];
            [object setDeleteTime:[rs stringForColumn:DairyBase_DeleteTime]];
            [object setDdat:[rs stringForColumn:DairyBase_Ddat]];
            [object setCryType:[NSNumber numberWithInt:[[rs stringForColumn:Crying_CryType] intValue]]];
            [object setTimeOfDay:[rs stringForColumn:Crying_TimeOfDay]];
            [object setCrySttime:[rs stringForColumn:Crying_CrySttime]];
            [object setCryEntime:[rs stringForColumn:Crying_CryEntime]];
            
            //添加对象到集合中
            [items addObject:object];
        }
        [db close];
    }];
    
    return items;
    
}

- (NSMutableArray *)getAppDisplayObjectModel
{
    DNDataBase *dnDB = [DNDataBase shareInstance];
    NSMutableArray *items = [[NSMutableArray alloc] init];
    [dnDB.dbQueue inDatabase:^(FMDatabase *db) {
        
        if(![db open])
        {
            db = nil;
            return;
        }
        else
            [db setKey:DB_SECRETKEY];
        
        NSString * queryString =  [self getQueryAppDisplayModelSqlWithTableName:Crying_TABLE];
        FMResultSet *rs = [db executeQuery:queryString];
        while ([rs next]) {
            DNCryingModel *object = [[DNCryingModel alloc] init];
            
            [object setAppId:[rs stringForColumn:DairyBase_AppId]];
            [object setServerId:[rs stringForColumn:DairyBase_ServerId]];
            [object setInfantId:[rs stringForColumn:DairyBase_InfantId]];
            [object setStatus:[NSNumber numberWithInt:[[rs stringForColumn:DairyBase_Status] intValue]]];
            [object setModifyTime:[rs stringForColumn:DairyBase_ModifyReason]];
            [object setDeleteReason:[rs stringForColumn:DairyBase_DeleteReason]];
            [object setCreateTime:[rs stringForColumn:DairyBase_CreateTime]];
            [object setModifyTime:[rs stringForColumn:DairyBase_ModifyTime]];
            [object setDeleteTime:[rs stringForColumn:DairyBase_DeleteTime]];
            [object setDdat:[rs stringForColumn:DairyBase_Ddat]];
            [object setCryType:[NSNumber numberWithInt:[[rs stringForColumn:Crying_CryType] intValue]]];
            [object setTimeOfDay:[rs stringForColumn:Crying_TimeOfDay]];
            [object setCrySttime:[rs stringForColumn:Crying_CrySttime]];
            [object setCryEntime:[rs stringForColumn:Crying_CryEntime]];
            
            //添加对象到集合中
            [items addObject:object];
        }
        [db close];
    }];
    
    return items;
    
}

#pragma mark - private motheds

- (DNCryingModel *) getObjectModelByOriginalModel:(DNCryingModel *)object
{
    DNCryingModel *cryingModel = [[DNCryingModel alloc] init];
    
    cryingModel.appId = [self getStringValueWithName:object.appId];
    cryingModel.serverId = [self getStringValueWithName:object.serverId];
    cryingModel.infantId = [self getStringValueWithName:object.infantId];
    cryingModel.status = [NSNumber numberWithInt:0];
    cryingModel.modifyReason = [self getStringValueWithName:object.modifyReason];
    cryingModel.deleteReason = [self getStringValueWithName:object.deleteReason];
    cryingModel.createTime = [self getStringValueWithName:object.createTime];
    cryingModel.modifyTime = [self getStringValueWithName:object.modifyTime];
    cryingModel.deleteTime = [self getStringValueWithName:object.deleteTime];
    cryingModel.ddat = [self getStringValueWithName:object.ddat];
    cryingModel.cryType =[NSNumber numberWithInt:0];
    cryingModel.timeOfDay = [self getStringValueWithName:object.timeOfDay];
    cryingModel.cryInyn = [self getStringValueWithName:object.cryInyn];
    cryingModel.crySttime = [self getStringValueWithName:object.crySttime];
    cryingModel.cryEntime = [self getStringValueWithName:object.cryEntime];
    cryingModel.appId = [self getStringValueWithName:object.appId];
    
    return cryingModel;
    
}

- (NSString *) getStringValueWithName:(id )fieldName{
    id value = fieldName;
    if(value == [NSNull null]){
        return @"";
    }else if( [value isKindOfClass:[NSString class]]){
        return (NSString *)value;
    }else if ([value isKindOfClass:[NSDecimalNumber class]]){
        return [value stringValue];
    }else if ([value isKindOfClass:[NSNumber class]]){
        return [value stringValue];
    }
    //    DDLogError(@"unexcepted json type %@", [value class]);
    return @"";
}

- (NSDate *) getDateValueWithName:(id )fieldName
{
    id value = fieldName;
    if(value == [NSNull null]){
        return [NSDate date];
    }
    return (NSDate *)fieldName;
}




@end
